﻿//     Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Configuration;
using System.IdentityModel.Claims;
using System.IdentityModel.Tokens;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Gateway.Utils;
using Microsoft.WindowsAzure;

namespace Gateway.Console
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AzureEnvironment.InitializeEnvironment(Configuration.AzureEnvironment);
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
            if (Configuration.IsAppInitialized)
            {
                RefreshValidationSettings();
            }
        }

        public static void RefreshValidationSettings()
        {
            RefreshValidationSettings(Configuration.Tenant);
        }

        public static void RefreshValidationSettings(string tenant)
        {
            try
            {
                string configPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Web.config";
                ValidatingIssuerNameRegistry.WriteToConfig(Configuration.FederationMetadataLocation.Replace("common", tenant), configPath);
            }
            catch
            {
            }
        }
    }
}
